package common;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * 登录过滤器：主要的作用是检查用户是否登录
 * 1.如果用户没有登录则跳转到登录页面
 * 2.如果用户已经登录则继续
 * 3.如果遇到图片文件、js文件、css文件的请求则继续
 * @author cqyhm
 *
 */
@WebFilter(urlPatterns={"/*"})
public class LoginFilter implements Filter {

	private Logger logger=LoggerFactory.getLogger(getClass());
	
	//指定哪些地址是不需要登录检查的
	private String[] ignoreUrls=new String[] {"login","register","register.do","css","images","js"};
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req=(HttpServletRequest)request;
		HttpServletResponse resp=(HttpServletResponse)response;
		String url=req.getRequestURI(); //过滤的请求地址
		
		//检查是否是需要忽略的请求
		boolean ignore=false;
		for (String str : ignoreUrls) {
			if(url.contains(str)) {
				ignore=true;
				break;
			}
		}
		//不需要做登录检查的地址
		if(ignore) {
			logger.info("不需要登录判断的地址:{},直接通过",url);
			chain.doFilter(req, resp);
		}else { //需要判断登录的地址(已经登录的用户会在session中存在user的值)
			HttpSession session=req.getSession();
			Object user=session.getAttribute("user");
			if(user!=null) {
				//已经登录的直接通过
				chain.doFilter(req, resp);
				logger.info("已经登录直接通过:{}",url);
			}else {
				//没有登录的跳转到登录页面
				logger.info("没有登录跳转到登录页面:{}",url);
				resp.sendRedirect(req.getContextPath()+"/login.jsp");
			}
		}
	}

	@Override
	public void destroy() {
	}

}
